package com.jeesite.modules.general.service;

import com.jeesite.common.codec.EncodeUtils;
import com.jeesite.common.codec.Sha1Utils;
import com.jeesite.common.service.CrudService;
import com.jeesite.modules.general.dao.GeneralDao;
import com.jeesite.modules.general.entity.UserInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Mr Wu
 * @date 2023/12/7
 */
@Service
public class GeneralService extends CrudService<GeneralDao, UserInfo> {

    @Transactional
    public String userLogin(UserInfo userInfo){
        List<UserInfo> listData = dao.getUserInfo(userInfo.getLoginCode());
        String msg = "无此用户!";
        if (listData.size()>0) {
            msg = "登录密码错误！";
            for (UserInfo info : listData) {
                boolean res = validatePassword(userInfo.getPassword(), info.getPassword());
                if (res) {
                    BeanUtils.copyProperties(info,userInfo);
                    msg = "登录成功！";
                    break;
                }
            }
            return msg;
        }
        return msg;

    }

    /**
     * 验证密码正确性
     * @param plainPassword 明文密码
     * @param password 密文密码
     * @return 验证成功返回true
     */
    public boolean validatePassword(String plainPassword, String password) {
        try{
            String plain = EncodeUtils.decodeHtml(plainPassword);
            byte[] salt = EncodeUtils.decodeHex(password.substring(0, 16));
            byte[] hashPassword = Sha1Utils.sha1(plain.getBytes(), salt, 1024);
            return password.equals(EncodeUtils.encodeHex(salt) + EncodeUtils.encodeHex(hashPassword));
        }catch(Exception e){
            return false;
        }
    }
}
